package zld369504.tw.m_team;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Headers;
import okhttp3.Response;
import zld369504.tw.m_team.api.MTeamHttpsApi;
import zld369504.tw.m_team.api.MTeamHttpsApiImpl;
import zld369504.tw.m_team.exception.MyException;

public class LoginActivity extends BaseActivity {

    private EditText etUserName;
    private EditText etPassword;

    private ProgressDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        etUserName = (EditText) findViewById(R.id.etUserName);
        etPassword = (EditText) findViewById(R.id.etPassword);
    }

    public void onLoginButtonClick(View view) {
        final String username = etUserName.getText().toString();
        final String password = etPassword.getText().toString();
        if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
            loadingDialog = ProgressDialog.show(this, "", "登录中...");
            Flowable.create(new FlowableOnSubscribe<String>() {
                @Override
                public void subscribe(FlowableEmitter<String> emitter) throws Exception {
                    MTeamHttpsApi api = MTeamHttpsApiImpl.getInstance();
                    Response response=api.login(username,password);
                    int responseCode = response.code();
                    if (responseCode == 302) {
                        Headers headers = response.headers();
                        List<String> valueList = headers.values("Location");
                        for (String s : valueList) {
                            if ((MTeamHttpsApiImpl.baseUrl + "/index.php").equals(s)) {
                                //login success
                                emitter.onNext("ok");
                                emitter.onComplete();
                            } else if ((MTeamHttpsApiImpl.baseUrl + "/login.php").equals(s)) {
                                MyException exception=new MyException("登录失败。用户名或者密码错误","");
                                emitter.onError(exception);
                            }
                        }
                    } else if(responseCode==200){
                        //已经登录成功了
                        emitter.onNext("ok");
                        emitter.onComplete();
                    } else {
                        MyException exception=new MyException("登录失败，未知错误！","");
                        emitter.onError(exception);
                    }
                }
            }, BackpressureStrategy.DROP)
                    .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<String>() {
                @Override
                public void onSubscribe(Subscription s) {
                    s.request(1);
                }

                @Override
                public void onNext(String s) {
                    loadingDialog.dismiss();
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("needLoadIndex", true);
                    startActivity(intent);
                    finish();
                }

                @Override
                public void onError(Throwable t) {
                    loadingDialog.dismiss();
                    showErrorDialog(t.toString());
                }

                @Override
                public void onComplete() {

                }
            });
        }
    }
}
